/**
 * @author janet
 * @date 2015-4-30
 */
package net.oscorner.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.oscorner.commons.ConstantUtil;

import org.springframework.web.filter.OncePerRequestFilter;


/**
 * @author janet
 * @date 2015-4-30 下午3:29:15
 * 
 */

public class CommonFilter extends OncePerRequestFilter {

	@Override
	protected void doFilterInternal(HttpServletRequest request,HttpServletResponse response, FilterChain chain)throws ServletException, IOException {
		// 不过滤的uri
		String[] notFilter = new String[] { "/login",".css",".js" };
		// 请求的uri
		String uri = request.getRequestURI().toLowerCase();
		// 从session中获取登录者实体
		Object obj = request.getSession().getAttribute("loginedUser");
		if (null == obj) {
			// 如果session中不存在登录者实体，则弹出框提示重新登录
			// 设置request和response的字符集，防止乱码
			request.setCharacterEncoding("UTF-8");
			response.setCharacterEncoding("UTF-8");
			boolean flag = false;
			for (String string : notFilter) {
				if(uri.indexOf(string) > -1)
					flag = true;
			}
			if(flag){
				chain.doFilter(request, response);
			}else{
				response.sendRedirect(ConstantUtil.BASEPATH+ "login");
			}
			
		} else {
			// 如果session中存在登录者实体，则继续
			if (uri.indexOf("/login") != -1) {
				response.sendRedirect(ConstantUtil.BASEPATH + "index");
			}
			chain.doFilter(request, response);
		}
	}

}
